﻿#region Copyright
// 
// Copyright (C) 2010 VirtualStaticVoid <virtualstaticvoid@gmail.com>
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
#endregion

namespace IoCWrap
{
  using System;
  using System.Reflection;

  public static class ContainerBuilderExtensions
  {

    public static void AddRegistry<TRegistry>(this IContainerBuilder builder)
      where TRegistry : IRegistry, new()
    {
      if (builder == null) throw new ArgumentNullException("builder");
      new TRegistry().Configure(builder);
    }

    public static void AddRegistry(this IContainerBuilder builder, IRegistry registry)
    {
      if (builder == null) throw new ArgumentNullException("builder");
      if (registry == null) throw new ArgumentNullException("registry");
      registry.Configure(builder);
    }

    public static void AddRegistriesFromAssembly(this IContainerBuilder builder, Assembly assembly)
    {
      if (builder == null) throw new ArgumentNullException("builder");
      if (assembly == null) throw new ArgumentNullException("assembly");
      LoadRegistries(builder, new[] { assembly });
    }

    public static void AddRegistriesFromAssemblies(this IContainerBuilder builder, params Assembly[] assemblies)
    {
      if (builder == null) throw new ArgumentNullException("builder");
      if (assemblies == null) throw new ArgumentNullException("assemblies");
      LoadRegistries(builder, assemblies);
    }

    public static void AddRegistriesFromAssemblyOf<TType>(this IContainerBuilder builder)
    {
      if (builder == null) throw new ArgumentNullException("builder");
      LoadRegistries(builder, new[] { typeof(TType).Assembly });
    }

    private static void LoadRegistries(IContainerBuilder containerBuilder, Assembly[] assemblies)
    {
      foreach (Type type in TypeFinder.FindConcreteTypesOf<IRegistry>(false, assemblies))
      {
        containerBuilder.Register((IRegistry)Activator.CreateInstance(type));
      }
    }

  }
}
